/*
 * Project Name spring-boot-tools
 * File Name MessageActionPool
 * Package Name com.huxiaosu.tools.cmpp.service
 * Create Time 2024/4/20
 * Create by name：liujie
 */
package com.huxiaosu.tools.cmpp.action;

import com.huxiaosu.tools.cmpp.enums.CommandId;
import com.huxiaosu.tools.common.holder.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description
 *
 * @author liujie
 * @date 2024/4/20 11:01
 */
@Slf4j
@Component
public class MessageActionPool implements ApplicationListener<WebServerInitializedEvent> {

    private static final Map<CommandId, MessageAction> MSG_COMMAND = new ConcurrentHashMap<>();

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        Map<String, MessageAction> beansOfType = SpringContextHolder.getBeansOfType(MessageAction.class);
        for (MessageAction action : beansOfType.values()) {
            MSG_COMMAND.put(action.getMessageCommandId(), action);
            log.info("MessageAction (commandId={}, action={}) register succeeded.",
                    action.getMessageCommandId().getCommand(), action.getMessageCommandName());
        }
    }

    public MessageAction getAction(CommandId commandId) {
        if (!MSG_COMMAND.containsKey(commandId)) {
            throw new RuntimeException(" commandId 不存在 ");
        }
        return MSG_COMMAND.get(commandId);
    }

    public static MessageActionPool getInstance() {
        return SpringContextHolder.getBean(MessageActionPool.class);
    }

}
